using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Musicman;
using Musicman.Utilities;
using System.Diagnostics;
using System.IO;
using Musicman.Entities.BusinessEntities;
using System.Configuration;
using Musicman.Common;
using System.Threading;
using Musicman.Business;
using System.Security.Cryptography;
using Musicman.Entities;

namespace MusicmanTest
{
    public partial class Form1 : Form
    {
        private FileFinder ff = null;
        private SearchJobConfigurationElement[] jobs;
        private SearchJobConfigurationElementCollection jobCollection = new SearchJobConfigurationElementCollection();
        private SearchLoactionConfigurationElementCollection locations = new SearchLoactionConfigurationElementCollection();

        public Form1()
        {
            InitializeComponent();

            ff = new FileFinder();
            ff.ProgressChanged+= new ProgerssChangedEventHandler(ff_ProgressChanged);
            ff.FileFindCompleted+= new FileFindCompletedEventHandler(ff_FileFindCompleted);

            SearchJobsConfigurationSection myJobs = (SearchJobsConfigurationSection)AppSettingsHelper.GetWebConfigSection("MyJobs");
            jobCollection = myJobs.Jobs;
            jobs = new SearchJobConfigurationElement[myJobs.Jobs.Count];
            myJobs.Jobs.CopyTo(jobs, 0);
            this.locations = myJobs.Locations;
        }

        void ff_FileFindCompleted(object sender, FileFindCompletedEventArgs e)
        {
            textBox3.AppendText(String.Format("Total time: {0} \r\nTotal files found: {1} \r\nTotal size: {2} \r\nTotal files added: {3} \r\nTotal files deleted: {4} \r\nTotal files modified: {5}\r\n", 
                e.TotalTime, e.TotalFiles, e.TotalFileSize, e.TotalAdded, e.TotalDeleted, e.TotalModified));
            if (this.jobCollection.Count != 0)
            {
                SearchJobConfigurationElement job = this.jobCollection[0];
                this.jobCollection.Remove(job);
                ff.SearchFilesAsync(job, this.locations);
            }
        }

        void ff_ProgressChanged(FileFindProgerssChangedEventArgs e)
        {
            if (label2.InvokeRequired || label3.InvokeRequired || label4.InvokeRequired)
            {
                ProgerssChangedEventHandler h = new ProgerssChangedEventHandler(ff_ProgressChanged);
                this.Invoke(h, new object[] { e });
            }
            else
            {
                label2.Text = String.Format("Current dir: {0}", e.CurrentDir);
            }
        }

        /*
        private void button3_Click(object sender, EventArgs e)
        {
            ff.SearchFielesAsync(SearchType.Local, "music", "*.mp3");
        }
        */

        private void button4_Click(object sender, EventArgs e)
        {
            if (this.jobCollection.Count != 0)
            {
                SearchJobConfigurationElement job = this.jobCollection[0];
                this.jobCollection.Remove(job);
                ff.SearchFilesAsync(job, this.locations);
            }
        }



        private void button6_Click(object sender, EventArgs e)
        {
            SearchJobsConfigurationSection jobSection = new SearchJobsConfigurationSection();
            SearchJobConfigurationElementCollection sjc = jobSection.Jobs;

            ExeConfigurationFileMap oConfigFile = new ExeConfigurationFileMap();
            oConfigFile.ExeConfigFilename = Application.StartupPath + "\\MusicmanTest.exe.config";
            Configuration oConfiguration = ConfigurationManager.OpenMappedExeConfiguration(oConfigFile, ConfigurationUserLevel.None); 
            
            for (int i = 0; i < sjc.Count; i++)
            {
                Musicman.Entities.BusinessEntities.SearchJobConfigurationElement job = sjc[i];
                textBox3.AppendText(job.Name);
            }
        }

        private void button7_Click(object sender, EventArgs e)
        {
            UpdateManager.Instance.RunSearchJob();
        }

        private void button8_Click(object sender, EventArgs e)
        {
            /*
            CronConfigurationSection cronSeciton = (CronConfigurationSection)AppSettingsHelper.GetWebConfigSection("CronConfig");
            textBox3.AppendText(cronSeciton.Settings.StartDate.ToString());
            textBox3.AppendText(cronSeciton.Settings.Days.ToString());
            textBox3.AppendText(cronSeciton.Settings.Hours.ToString());
            textBox3.AppendText(cronSeciton.Settings.Minutes.ToString());
             * */
            UpdateManager.Instance.StartCron();
            // textBox3.AppendText(UpdateManager.Instance.nextDate.ToString() + "\r\n");
        }

        private void button9_Click(object sender, EventArgs e)
        {
            UpdateManager.Instance.StopCron();
            
        }

        private void button1_Click(object sender, EventArgs e)
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback(RunUpdate));
        }


        private void RunUpdate(object o)
        {
            List<Musicman.Entities.Searchjob> allJobs = DataManager.Instance.GetAllSearchJobs();
            for (int i = 0; i < allJobs.Count; i++)
            {
                Musicman.Entities.Searchjob job = allJobs[i];
                List<SearchResult> files = DataManager.Instance.SearhFiles((long)job.Searchjobid , "");
                this.progressBar1.Value = 0;
                this.progressBar1.Maximum = files.Count;
                for (int j = 0; j < files.Count; j++)
                {
                    if (File.Exists(files[j].Fullpath))
                    {
                        Musicman.Entities.Searchfile sf = DataManager.Instance.GetSearchFile(files[j].FileID);
                        if (sf != null)
                        {
                            FileInfo fi = new FileInfo(files[j].Fullpath);
                            sf.Length = fi.Length;
                            DataManager.Instance.SaveSearchFile(sf);
                        }
                    }
                    this.progressBar1.Value = j;
                }
            }
            this.progressBar1.Value = 0;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            GC.Collect();
        }

        private void toolStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {

        }

        private void button5_Click(object sender, EventArgs e)
        {

        }

        private void tabPage3_Click(object sender, EventArgs e)
        {

        }

        static public string PassEncrypting(string originalPass)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            Byte[] originalBytes;
            Byte[] encodedBytes;
            originalBytes = ASCIIEncoding.Default.GetBytes(originalPass);
            encodedBytes = md5.ComputeHash(originalBytes);
            return BitConverter.ToString(encodedBytes);
        } 

        private void button10_Click(object sender, EventArgs e)
        {
            string original = txtLove.Text;
            string encoded = PassEncrypting(original);

            string message = String.Format("{0} --> {1}", original, encoded);
            MessageBox.Show(message, "Love", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void button11_Click(object sender, EventArgs e)
        {
            List<User> users = DataManager.Instance.GetAllUsers();
            for (int i = 0; i < users.Count; i++)
            {
                User user = users[i];
                user.Password = PassEncrypting(user.Password);
                DataManager.Instance.SaveUser(user);
            }
        }

        private void button12_Click(object sender, EventArgs e)
        {
            string[] files = Directory.GetFiles("D:\\Programiranje\\CSharp\\CSManager\\CSManager.Windows\\", "*.cs;*.config");

            for (int i = 0; i < files.Length; i++)
            {
                textBox1.AppendText(files[i]);
                textBox1.AppendText("\r\n");
            }

            DirectoryInfo dinfo = new DirectoryInfo("D:\\Programiranje\\CSharp\\CSManager\\CSManager.Windows\\");
            FileInfo[] finfos = dinfo.GetFiles("*.cs *.config");
            for (int i = 0; i < finfos.Length; i++)
            {
                textBox1.AppendText(finfos[i].Name);
                textBox1.AppendText("\r\n");
            }



        }
    }
}